# server.py
import sys
import json
import logging
import paho.mqtt.client as mqtt
import threading
from mcp.server.fastmcp import FastMCP

# 配置日志
logger = logging.getLogger('Home Assistant MCP')
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# Fix UTF-8 encoding for Windows console
if sys.platform == 'win32':
    sys.stderr.reconfigure(encoding='utf-8')
    sys.stdout.reconfigure(encoding='utf-8')

# MQTT配置
MQTT_CONFIG = {
    "broker_address": "broker.emqx.io",
    "broker_port": 1883,
    "username": None,
    "password": None,
}

client = mqtt.Client()  # 创建MQTT客户端实例

def on_connect(client, userdata, flags, rc):
    logger.info(f"Connected with result code {rc}")
    client.publish("ha/ai", "Hello MQTT")  # 连接后发布消息
    client.subscribe("ha/ai")  # 订阅主题以接收消息

def on_message(client, userdata, message):
    try:
        payload = message.payload.decode()
    except UnicodeDecodeError:
        payload = f"<无法解码的消息内容: {message.payload}>"
    logger.info(f"Received message: {payload} on topic {message.topic}")

def init_mqtt():
    try:
        client.on_connect = on_connect
        client.on_message = on_message
        if MQTT_CONFIG["username"] and MQTT_CONFIG["password"]:
            client.username_pw_set(MQTT_CONFIG["username"], MQTT_CONFIG["password"])
        ret = client.connect(MQTT_CONFIG["broker_address"], MQTT_CONFIG["broker_port"], 60)
        logger.error(f"MQTT连接: {ret}")
        client.loop_forever()
    except Exception as e:
        logger.error(f"MQTT连接失败: {e}")
        sys.exit(1)

# Create an MCP server
mcp = FastMCP("Home Assistant MCP")

# Add a lamp control tool
@mcp.tool()
def switchLamp(on_off: bool) -> dict:
    """这是一个用于控制HomeAssistant的灯的接口"""
    result = "开灯成功" if on_off else "关灯成功"
    logger.info(f"switchLamp formula: {on_off}, result: {result}")
    status = 1 if on_off else 0
    payload = json.dumps({"status": status})
    client.publish("ha/ai", payload)  # 连接后发布消息
    return {"success": True, "result": result}

# Start the server
if __name__ == "__main__":
     # 启动 MQTT 客户端在单独的线程中
    mqtt_thread = threading.Thread(target=init_mqtt, daemon=True)
    mqtt_thread.start()
    mcp.run(transport="stdio")